﻿using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows;

namespace Adjunct.Generator
{
	public class EntryPoint
	{
		static EntryPoint()
		{
			AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
			AppDomain.CurrentDomain.UnhandledException += DisplayUnhandledException;
		}

		[STAThread]
		public static void Main(string[] args)
		{
			App.Main();
		}

		private static void DisplayUnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			MessageBox.Show(e.ExceptionObject.ToString());
		}

		private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			AssemblyName requestedAssemblyName = new AssemblyName(args.Name);
			string path = requestedAssemblyName.Name + ".dll";

			if (requestedAssemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false)
			{
				path = String.Format(@"{0}\{1}", requestedAssemblyName.CultureInfo, path);
			}

			using (Stream stream = executingAssembly.GetManifestResourceStream(path))
			{
				if (stream == null)
				{
					return null;
				}

				byte[] assemblyRawBytes = new byte[stream.Length];
				stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
				return Assembly.Load(assemblyRawBytes);
			}
		}
	}
}